﻿/*
%include "/projects/hsieh_project/proj_201809/code_1_data/m_read_sale.sas" /source2;

Macro that loads merged EC and LBD data. Counterpart to m_read.sas.

param_dev = whether we are in development mode (not used)
param_lyear = the list of years to keep
param_czone = whether to merge with czone
param_msacz = whether to merge with msa*cz
param_drop = whether to drop additional industries
*/

libname plec "/projects/data_commons/ec/";

%macro m_read_sales(param_dev=0, param_lyear=%quote(1977,2013), param_czone=0, param_msa1983=0, param_msacz=0, param_drop=1);

/*
--------------------------------------------------------------------------------
Load selected data
*/

data lbd;
  set plec.ec_lbd_clean_merge;
  if in_lbd = 1 & in_ec = 1;
run;

/* Subset Years */
%if "&param_lyear." ~= "0" %then %do;
data lbd;
  set lbd;
  if year in (&param_lyear.);
run;
%end;

%include "/projects/hsieh_project/proj_201809/code_1_data/data_0_read_raw.sas" /source2;

/*
--------------------------------------------------------------------------------
Merge with commuting zones
*/

%if &param_czone. = 1 %then %do;
proc import out=cw_geo datafile="/projects/data_commons/cw/cw_geo_fips_czone_v12.dta" replace;
run;

proc sort data=lbd; by fips;
proc sort data=cw_geo; by fips;

data lbd;
  merge lbd(in=x) cw_geo;
  by fips;
  if x = 1;
run;

%end;

/*
--------------------------------------------------------------------------------
Merge with hybrid MSA1983
*/

%if &param_msa1983. = 1 %then %do;

proc import out=cw_geo(keep=fips msa1983) datafile="/projects/data_commons/cw/cw_geo_fips_msa1983_v12.dta" replace;
run;

proc sort data=lbd; by fips;
proc sort data=cw_geo; by fips;

data lbd;
  merge lbd(in=x) cw_geo;
  by fips;
  if x = 1;
run;

%end;

/*
--------------------------------------------------------------------------------
Merge with hybrid MSA-CZONE
*/

%if &param_msacz. = 1 %then %do;

proc import out=cw_geo datafile="/projects/data_commons/cw/cw_geo_fips_msa_czone_v12.dta" replace;
run;

proc sort data=lbd; by fips;
proc sort data=cw_geo; by fips;

data lbd;
  merge lbd(in=x) cw_geo;
  by fips;
  if x = 1;
run;

%end;

/*
REDACTED
Code related to dropping of a specific industry is redacted */



/*
--------------------------------------------------------------------------------
Prepare random variable
*/

data lbd;
  set lbd;
  runif=runif_1;
run;

/*
--------------------------------------------------------------------------------
Add rank by sales
--------------------------------------------------------------------------------
*/

%m_perc_by_var(ds_in=lbd, ds_out=lbd_indf, var_in=sales, var_by=%bquote(year ch_ind), var_unit=firmnum, var_out=sales_indf, var_runif=runif_1);


proc sort data=lbd; by year firmnum ch_ind;
proc sort data=lbd_indf; by year firmnum ch_ind;

data lbd;
  merge lbd lbd_indf;
  by year firmnum ch_ind;
run;

%mend;

/* End of SAS file */
